<?php

class Content_Page_Main_Edit extends Content_Page_Main {

	protected function URL($array = array()){
		return parent::URL(array_merge(
			array($this->content->id(), 'edit'),
			$array
		));
	}

	public function rid($array = array()){
		return parent::rid(array_merge(
			array($this->content->id(), 'edit'),
			$array
		));
	}

	protected function __construct($args){
		parent::__construct($args);

		$this->content = Content::GetByID($args['id']);

		$language = Authentication::getInstance()->user()->language();

		$this->form = new Form(array('content', $this->content->id(),'edit'), $this->URL());

		$title = Form_Field::Create('title','text');
		$title->title($language->translate(array('content','title')));
		$title->value($this->content->title());
		$title->validate('not_empty');
		$this->form->add($title);

		$body = Form_Field::Create('body',array('richtext','textarea'));
		$body->title($language->translate(array('content','body')));
		$body->value($this->content->body());
		$this->form->add($body);

		$continue = Form_Field::Create('continue','checkbox');
		$continue->title($language->translate(array('content','continue')));
		
		$cont = isset($_SESSION['content'][$this->content->id()]['continue']) ? $_SESSION['content'][$this->content->id()]['continue'] : false;

		unset($_SESSION['content'][$this->content->id()]['continue']);

		$continue->value($cont);
		$this->form->add($continue);

		$submit = Form_Field::Create('submit','submit');
		$submit->title($language->translate(array('content','update')));

		$this->form->add($submit);
	}

	public static function Load($args){
		$page = new Content_Page_Main_Edit($args);
		return $page;
	}

	public function run(){
		parent::run();
		$this->form->run();

		try {
			$data = $this->form->data();
			$this->content->update(array('title' => $data['title'], 'body' => $data['body']));

			if($data['continue']){
				$_SESSION['content'][$this->content->id()]['continue'] = true;
				CMS::Redirect($this->URL());
			} else {
				unset($_SESSION['content'][$this->content->id()]['continue']);
				CMS::Redirect(parent::URL(array($this->content->id(),'view')));
			}
		} catch(Exception $e){}
	}

	public function output($child = null){
		$template = Output::getInstance()->Template(array('content','page','edit'));
		$template->title = $this->content->title();
		$template->form = $this->form->output();
		return parent::output($template);
	}

}
